;
(function() {
    //把select里面的option数据 转换为一个data数组[{value:'',text:''}]
    function getSelectDatalist(_select) {
        var data = [];
        _select.find('option').each(function() {
            var _text = $(this).text();
            var _value = $(this).val();
            data.push({ text: _text, value: _value });
        });
        if (!data.length) {
            var _prompt = _select.attr('data-prompt') || '请选择';
            data.push({
                text: _prompt,
                value: ''
            });
        }
        return data;
    }

    //获取10位长度的随机字符串 由数字和英文字母组成
    function createZboxId() {
        var zid = '';
        var wds = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('');
        for (var i = 0; i < 10; i++) {
            zid += (wds[Math.floor(Math.random() * wds.length)]);
        }
        return zid;
    }

    function resizeList(){
        $('.z-select').each(function(_i,_vt){
            if($(_vt).attr('relative-parent') == 'window'){
                if(!$(_vt).zsGetList()){return true;}
                $(_vt).zsGetList().css({
                    top:$(_vt).zsGetBox().offset().top -(-$(_vt).zsGetBox().innerHeight())+'px',
                    left:$(_vt).zsGetBox().offset().left+'px',
                    width:$(_vt).zsGetBox().innerWidth()+'px'
                });
            }
        })
    }

    $.fn.extend({
        zSelect: function(opts) {
            opts = opts ? opts : {};
            return $(this).each(function(k, v) {
                var _v = $(v);
                if (_v.is('select')) {
                    if (_v.attr('isInited') === 'yes') {
                        return;
                    }
                    _v.attr('isInited', 'yes');
                    _v.hide();
                    var data = getSelectDatalist(_v);
                    var _value = _v.attr('data-value') || _v.val() || '';
                    var _name = _v.attr('name') || '';
                    var _skin = _v.attr('data-skin') || '';
                    var _content = _v.attr('data-content') || false;
                    var _style = _v.attr('data-style') || '';
                    var zbox_id = createZboxId();
                    _v.data('zbox_id', zbox_id);
                    _v.addClass('zbox-id-' + zbox_id);
                    _v.attr('name', '');
                    var _zbox_dom = '';
                    if (_content) {
                        _zbox_dom += '<div data-zbox-id="' + zbox_id + '" class="zs-box ' + _skin + ' zbox-' + zbox_id + '" ' + (_style != '' ? 'style="' + _style + '"' : '') + '><div contenteditable="' + _content + '" class="zs-value">请选择</div><i class="zs-down-ico"></i><input class="zs-input" name="' + _name + '" value="" type="hidden"/>';
                        _zbox_dom += (_v.attr('relative-parent') != 'window')?'<ul class="zs-list"></ul>':'';
                        _zbox_dom += '</div>';
                    } else {
                        _zbox_dom += '<div data-zbox-id="' + zbox_id + '" class="zs-box ' + _skin + ' zbox-' + zbox_id + '" ' + (_style != '' ? 'style="' + _style + '"' : '') + '><div class="zs-value">请选择</div><i class="zs-down-ico"></i><input class="zs-input" name="' + _name + '" value="" type="hidden"/>';
                        _zbox_dom += (_v.attr('relative-parent') != 'window')?'<ul class="zs-list"></ul>':'';/**下拉相对窗口absolute时 */
                        _zbox_dom += '</div>';
                    }
                    _v.after(_zbox_dom);
                    if(_v.attr('relative-parent') == 'window'){
                        _v.data('zbox_panel',$("<ul class=\"zs-panel-list zs-list\" list-id='"+zbox_id+"'></ul>").appendTo("html>body"));
                    }else{
                        _v.data('zbox_panel', _v.zsGetBox().find('.zs-list'));
                    }

                    _v.zsSetData(data, {});
                    _v.zsGetBox().setZsValue(_value);
                    if (v.disabled) {
                        _v.zsGetBox().setZsDisabled(true);
                    }

                    $(window).on('resize',function(){
                        resizeList();
                    });
                    resizeList();
                }
            });
        },
        setZsValue: function(_value) {
            return $(this).each(function(k, v) {
                var _v = $(v);
                if (_v.is('select')) {
                    _v.zsGetBox().setZsValue(_value);
                } else if (_v.is('.zs-box')) {
                    _v.zsGetList().find('.zs-item.current').removeClass('current');
                    var _item = _v.zsGetList().find('.zs-item[v="' + _value + '"]').addClass('current');
                    var _text = _v.find('.zs-value').attr('placeholder') || '请选择';
                    if (_item.length) {
                        _text = _item.attr("title");
                    } else {
                        _value = '';
                    }
                    _v.find('.zs-value').text(_text).attr('title', _text);
                    _v.find('.zs-input').val(_value);
                    $('.zbox-id-' + _v.attr('data-zbox-id')).trigger('setZsValue');
                }
            });
        },
        getZsValue: function() {
            if ($(this).is('select')) {
                return $(this).zsGetBox().find('.zs-input').val();
            } else if ($(this).is('.zs-box')) {
                return $(this).find('.zs-input').val();
            }
            return '';
        },
        setZsDisabled: function(isdisb) {
            var _abled = $(this).zsGetBox().find('.zs-value');

            if (_abled.attr('contenteditable')) {
                if ((isdisb && _abled.attr('contenteditable') == 'true') || $(this).zsGetBox().hasClass('readonly')) {
                    _abled.attr('contenteditable', false);
                } else if (!isdisb && _abled.attr('contenteditable') == 'false') {
                    _abled.attr('contenteditable', true);
                }
            }
            return isdisb ? $(this).zsGetBox().addClass('zs-disabled') : $(this).zsGetBox().removeClass('zs-disabled');
        },
        zsGetBox: function() {
            var _t = $(this);
            if (_t.is('select')) {
                var zbox_id = _t.data('zbox_id');
                if (zbox_id) {
                    return $('.zbox-' + zbox_id);
                } else {
                    return $();
                }
            } else if (_t.is('.zs-box')) {
                return _t;
            }
        },
        zsGetList: function(){
            var _t = $(this);
            if (_t.is('select')) {
                return _t.data('zbox_panel');
            } else if (_t.is('.zs-box')) {
                var zbox_id = _t.attr('data-zbox-id');
                return $('.z-select.zbox-id-'+zbox_id).data('zbox_panel');
            }
        },
        zsLoadData: function(opts) {
            return $(this).each(function(k, v) {
                var _v = $(v);
                $.ajax({
                    url: opts.url,
                    type: 'get',
                    dataType: 'json',
                    success: function(data) {
                        var _prompt = _v.attr('data-prompt');
                        var _data = [];
                        if (opts.dataFitler) {
                            data = opts.dataFitler(data);
                        }
                        try {
                            if (!opts.dataFitler && data.rows) { data = data.rows; }
                        } catch (e) {}
                        if (_prompt) {
                            var item = {};
                            if (opts.valueField) {
                                item[opts.valueField] = '';
                            } else {
                                item['value'] = '';
                            }
                            if (opts.textField) {
                                item[opts.textField] = _prompt;
                                item['text'] = _prompt;
                            }

                            _data = [item].concat(data);
                        } else {
                            _data = data;
                        }
                        _v.zsSetData(_data, opts);
                        _v.trigger('dataSeted');
                    }
                });
            });
        },
        zsSetData: function(dataList, opts) {
            return $(this).each(function(k, v) {
                var _v = $(v);
                if(dataList.length>1){
                    if(!_v.attr('loaded_dt') && _v.zsGetBox().find('.zs-value').attr('contenteditable') == 'true'){
                        //绑定过滤事件
                        _v.attr('loaded_dt',true);
                        _v.selectauto(opts, dataList);
                    }
                }
                var _list = '';

                if(typeof opts.groupField!='undefined' && opts.groupField!=''){
                    var newarr = [];
                    var _group = opts.groupField;
                    var _funfindIndex = function(txt){
                        var bomIndex = -1;
                        if(newarr.length>0){
                            $.each(newarr,function(i,m){
                                if(m.text == txt){
                                    bomIndex = i;
                                    return false;
                                }
                            })
                        }
                        return bomIndex;
                    }
                    $.each(dataList, function(index, cell) {
                        if(cell[_group]){
                            var ccell = {};
                            ccell[opts.valueField] = cell[opts.valueField];
                            ccell[opts.textField] = cell[opts.textField];
                            var cindex = _funfindIndex(cell[_group]);
                            if(cindex>-1){
                                newarr[cindex].children.push(ccell);
                            }else{
                                newarr.push({
                                    value: _group+'_'+index,
                                    text: cell[_group],
                                    children: [ccell]
                                })
                            }
                        }else{
                            newarr.push({
                                value: cell[opts.valueField],
                                text: cell[opts.textField]
                            })
                        }
                    });
                    // console.log(newarr,'----有group',opts);
                    $.each(newarr, function(index, itemnew){
                        var __v = itemnew['value'];
                        var __text = itemnew['text'];
                        _list += ('<li class="'+(itemnew.children?'zs-itemgroup':'zs-item')+'" v="' + __v + '" title="' + __text + '">' + __text + '</li>');
                        if(itemnew.children){
                            $.each(itemnew.children, function(indexv, itemv){
                                _list += ('<li class="zs-item levelchild" v="' + itemv[opts.valueField] + '" title="' + itemv[opts.textField] + '">' + itemv[opts.textField] + '</li>');
                            })
                        }
                    })
                }else{
                    $.each(dataList, function(index, item) {
                        var __v = item[opts.valueField || 'value'];
                        var __text = item[opts.textField || 'text'];
                        
                        if (item[opts.fletterField || 'fletter'] && typeof item[opts.fletterField || 'fletter'] != 'undefined') {
                            var __text2 = item[opts.fletterField || 'fletter'] + '-' + item[opts.textField || 'text'];
                        } else {
                            var __text2 = __text;
                        }

                        _list += ('<li class="zs-item" v="' + __v + '" title="' + __text + '">' + __text2 + '</li>');
                    });
                }
                _v.zsGetList().empty().append(_list);
                if (opts.setValue) {
                    _v.zsGetBox().setZsValue(opts.setValue);
                }
                
            });
        }
    });

    $.extend({
        zSelectGroup: function(zsList) {
            function copyItem(item) {
                var newItem = {};
                for (var i in item) {
                    newItem[i] = item[i];
                }
                return newItem;
            }

            $.each(zsList, function(index, item) {
                var _item = copyItem(item);
                _item.initValue = _item.setValue;
                _item.initDisabled = _item.setDisabled;
                _item.setValue = '';
                if (index == 0) {
                    _item.elem.zsLoadData(_item);
                } else {
                    _item.elem.zsGetBox().setZsDisabled(true);

                    var parent = zsList[index - 1];
                    parent.elem.on('setZsValue', function() {
                        var _value = parent.elem.getZsValue();
                        _item.elem.zsGetBox().setZsValue('');
                        if (_value) {
                            _item.url = item.url.replace('@parentValue', _value);
                            _item.elem.zsLoadData(_item).zsGetBox().setZsDisabled(false);
                        } else {
                            _item.elem.zsGetBox().setZsDisabled(true);
                        }
                    });
                }
                _item.elem.one('dataSeted', function() {
                    if (_item.initValue) {
                        _item.elem.zsGetBox().setZsDisabled(_item.initDisabled ? _item.initDisabled : false).setZsValue(_item.initValue);
                    }
                });
            });
        }
    });

    $(function() {
        $(document).on('click', function(e) {
            var _tg = $(e.target);
            if(_tg.hasClass('zs-itemgroup')){
                return;
            }
            if (!(_tg.hasClass('zs-box') || _tg.parents('.zs-box').length)) {
                $('.zs-box').each(function(_k, _t) {
                    var _pt = $('select.zbox-id-' + $(_t).attr('data-zbox-id'));
                    if ($.trim($(_t).find('.zs-input').val()) == '') {
                        $(_t).find('.zs-value').attr('title', _pt.attr('data-prompt') || '请选择').text(_pt.attr('data-prompt') || '请选择');
                    }
                    $(_t).removeClass('active');
                    _pt.zsGetList().removeClass('active');
                })
            }
        });
        $(document).on('click', '.zs-box', function(e) {
            $('body').find('.select-defined').removeClass('active');
            var _t = $(this);
            var _tg = $(e.target);
            if(_tg.hasClass('zs-itemgroup')){
                return;
            }
            if (_t.hasClass('zs-disabled') || _t.hasClass('readonly')) {
                return;
            }
            $('.zs-box').not(this).removeClass('active');
            $('.zs-panel-list').each(function(){
                if($(this).attr('list-id') !=_t.attr('data-zbox-id')){
                    $(this).removeClass('active');
                }
            })
            _t.toggleClass('active').removeClass('active-top');
            var _list = _t.zsGetList();
            _list.toggleClass('active').removeClass('active-top');
            if(_list.hasClass('zs-panel-list')){
                _list.css({
                    top:_t.offset().top -(-_t.innerHeight())+'px',
                    left:_t.offset().left+'px'
                });
                return false;
            }
            if (_list.offset().top + _list.height() > $(window).scrollTop() + $(window).height()) {
                _t.addClass('active-top');
            }
        });
        $(document).on('click', '.zs-list .zs-item', function() {
            var _value = $(this).attr('v');
            var _l = $(this).parents('.zs-list');
            if(_l.hasClass('zs-panel-list')){
                var _box_id = _l.attr('list-id');
                $('.zs-box[data-zbox-id="'+_box_id+'"]').setZsValue(_value);
                $('.zs-box[data-zbox-id="'+_box_id+'"]').toggleClass('active').removeClass('active-top');
                $('.zs-box[data-zbox-id="'+_box_id+'"]').zsGetList().toggleClass('active').removeClass('active-top');
                return false;
            }
            $(this).parents('.zs-box').setZsValue(_value);
        });

        if ($('.z-select')) {
            $('.z-select').zSelect();
        }
    });

    function _bindEd(_s) {
        /**
         * [_s select元素] 初始化下拉框时 给编辑框绑定操作事件
         * 事件包括 inputEvents中 鼠标点击和键盘事件
         */
        var _d = _s.data('selectauto');
        var _b = _s.zsGetBox().find('.zs-value');
        var _c = _d.conf;

        var _p = _s.attr('data-prompt') || '请选择';
        _b.attr("placeholder", _p);
        _b.off('.autoselect');

        for (var evt in _c.inputEvents) {
            _b.on(evt + '.autoselect', { target: _b, father: _s }, _c.inputEvents[evt]);
        }
    }

    function _e_blur(e) {
        var t = $(e.data.target);
        var _s = $('select.zbox-id-' + t.parents('.zs-box').attr('data-zbox-id'));
        var zbox = _s.zsGetBox();
        var _v = zbox.find('.zs-input').val();
        if (_v == '' && !zbox.hasClass('active')) {
            t.text(t.attr('placeholder'));
        }
        return false;
    }

    function _e_click(e) {
        var t = $(e.data.target);
        if (t.parent('.zs-box').hasClass('zs-disabled') || t.parent('.zs-box').hasClass('readonly') || !t.attr('contenteditable')) {
            return;
        }
        t.attr('title', '');

        // $('.zs-box').not(t.parents('.zs-box')).removeClass('active');
        $('.zs-box').not(t.parents('.zs-box')).each(function(){
            var _tt = $(this);
            $(this).removeClass('active');
            var _zs_v = _tt.find('.zs-value');
            if(_tt.find('.zs-input').val() == '' && _zs_v.attr('contenteditable') == 'true'){
                _zs_v.attr('title', _zs_v.attr('placeholder'));
                _zs_v.text(_zs_v.attr('placeholder'));
            }
        });
        var _s = $('select.zbox-id-' + t.parents('.zs-box').attr('data-zbox-id'));
        if (t.text().indexOf('请选择') > -1) {
            t.text('');
        }
        _s.selectauto('showList', t.parents('.zs-box').find('.zs-input').val()!=''?true:false);
        _s.data('selectauto').conf.keyHandler.query.call(t, e);
        return false;
    }

    function _write_in(e) {
        var t = e.data.target;
        var _b = $(t); //txt box
        var _s = $(e.data.father); //select
        var _d = _s.data('selectauto'); //all configs
        var _c = _d.conf; //defaults
        if (e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13 && e.keyCode != 9 && e.keyCode != 27) {
            if (_d.timer) {
                clearTimeout(_d.timer);
            }
            _d.timer = setTimeout(function() {
                var _v = _b.text();
                if (_d.previousText != _v) {
                    _d.previousText = _v;
                    _s.selectauto('showList');
                    _c.keyHandler.query.call(t, e);
                }
            }, 300);
        }
    }

    function _events(e) {
        var t = e.data.target;
        var _b = $(t); //txt box
        var _s = $(e.data.father); //select
        var _d = _s.data('selectauto'); //all configs
        var _c = _d.conf; //defaults

        switch (e.keyCode) {
            case 38:
                e.preventDefault();
                e.stopPropagation();
                _c.keyHandler.up.call(t, e);
                break;
            case 40:
                e.preventDefault();
                e.stopPropagation();
                _c.keyHandler.down.call(t, e);
                break;
            case 13:
                e.preventDefault();
                _c.keyHandler.enter.call(t, e);
                return false;
                break;
            case 9:
            case 27:
                // close select;
                _c.keyHandler.close.call(t, e);
                break;
            default:
                ;
        }
    }

    function to_Last_Div(t) {
        if (window.getSelection) {
            t.focus();
            var range = window.getSelection();
            range.selectAllChildren(t);
            range.collapseToEnd();
        } else if (document.selection) {
            var range = document.selection.createRange();
            range.moveToElementText(t);
            range.collapse(false);
            range.select();
        }
    }

    function up2down(_t, type) {
        /**
         * [键盘上下键控制下拉内元素上下选中]
         * @_t {可编辑框div元素}
         * @type {键盘上下时类型}
         */
        var _s = $('select.zbox-id-' + _t.parents('.zs-box').attr('data-zbox-id'));
        var zbox = _s.zsGetBox();
        var zlist = zbox.zsGetList();
        var _v = zbox.find('.zs-input').val();
        if (!zlist || !zlist.find('li')) { return false; }
        if (type == 'up') {
            var _tocell = zlist.find('li.current').prev('li');
            var _row = _tocell.length > 0 ? _tocell : zlist.find('li').last();
            if(_row.hasClass('zs-itemgroup')){
                _row = _row.prev('li');
            }
        }
        if (type == 'down') {
            var _tocell = zlist.find('li.current').next('li');
            var _row = _tocell.length > 0 ? _tocell : zlist.find('li').first();
            if(_row.hasClass('zs-itemgroup')){
                _row = _row.next('li');
            }
        }
        _row.addClass('current').siblings('li.current').removeClass('current');
        zbox.find('.zs-input').val(_row.attr('v'));


        var _txt = _s.selectauto('getBoxText', _row.attr('v'));
        zbox.find('.zs-value').text(_txt);

        _t.focus();
        to_Last_Div(_t[0]);
        return false;
    }

    function filterData(s, _v) {
        /**
         * [根据输入值 过滤下拉列表内容]
         * @_v {当前可编辑div内的输入值}
         */
        var _d = s.data('selectauto');
        var _list = _d.data;
        var _able = s.zsGetBox().find('.zs-value').attr('contenteditable');
        if (typeof(_able) == 'string' && _able != 'true') {
            return _list;
        }

        var field = {
            valueField: _d.conf.valueField,
            textField: _d.conf.textField
        };
        _d.previousText = _v;
        if ($.trim(_v) == '') { return _list; }
        var _vs = [];
        for (var a in _list) {
            if (_list[a][field.textField].toLowerCase().indexOf($.trim(_v.toLowerCase())) > -1) {
                _vs.push(_list[a]);
            }
        }
        return _vs;
    }

    $.fn.selectauto = function(opts, dataList) {
        var _this = this;
        if (typeof opts == "string") {
            //调用methods方法时
            var _fun = $.fn.selectauto.methods[opts];
            if (_fun) {
                return _fun(_this, dataList);
            } else {
                return _this;
            }
        }
        var confs = $.extend({}, $.fn.selectauto.defaults, opts);
        // return this.each(function(k, v) {
            var _v = $(this);
            var opt = $.fn.selectauto.methods['getOptions'];
            
            if (opt) {
                _v.data('selectauto', {
                    conf: confs,
                    list: dataList,
                    data: opt(confs.textField, dataList)
                });
            }
            _bindEd(_v);
        // })
    }

    $.fn.selectauto.methods = {
        getAjaxData: function(_url, cbk) {
            $.get(_url, function(result) {
                cbk(result);
            })
        },
        getOptions: function(txt, _data) {
            return $.map(_data, function(_itm) {
                return _itm;
            });
        },
        getBoxText: function(s, id) {
            var _data = s.data('selectauto');
            var _conf = _data.conf;
            var _list = _data.data;
            var vField = _conf.valueField;
            var tField = _conf.textField;

            var _txt = '';
            for (var v in _list) {
                if (_list[v][vField] == id) {
                    _txt = _list[v][tField];
                }
            }
            return _txt;
        },
        getBoxVal: function(s, txt) {
            // debugger;
            var _data = s.data('selectauto');
            var _conf = _data.conf;
            var _list = _data.data;
            var vField = _conf.valueField;
            var tField = _conf.textField;
            var _id = '';
            for (var v in _list) {
                if (_list[v][tField] == txt) {
                    _id = _list[v][vField];
                }
            }
            return _id;
        },
        setInputVal: function(t) {
            var _s = $('select.zbox-id-' + t.parents('.zs-box').attr('data-zbox-id'));
            var zbox = _s.zsGetBox();
            var _txt = $.trim(zbox.find('.zs-value').text());
            var _v = _s.selectauto('getBoxVal', _txt);
            if (_v != '') {
                _s.zsGetList().find('li').each(function(_k, itm) {
                    if ($(itm).attr('v') == _v) {
                        zbox.find('.zs-input').val(_v == '' ? _txt : _v);
                        $(itm).addClass('current').siblings('li.current').removeClass('current');
                    }
                })
            }
        },
        showList: function(jq, all) {
            return jq.each(function() {
                var zbox = $(this).zsGetBox();
                var tbox = zbox.find('.zs-value');
                var _d = $(this).data('selectauto');
                var fields = {
                    valueField: _d.conf.valueField,
                    textField: _d.conf.textField
                };
                if(_d.conf.groupField){
                    fields.groupField = _d.conf.groupField;
                }
                // console.log(_d.conf,'---_d.conf');
                var _data = filterData($(this), tbox.text());
                if(all){
                    _data = _d.data;
                }
                
                $(this).zsSetData(_data, fields);
                zbox.find('.zs-input').val('');

                if (_data.length > 0) {
                    zbox.addClass('active');
                    $(this).zsGetList().addClass('active');
                    if($(this).zsGetList().hasClass('zs-panel-list')){
                        $(this).zsGetList().css({
                            top:zbox.offset().top -(-zbox.innerHeight())+'px',
                            left:zbox.offset().left+'px'
                        });
                    }
                } else {
                    zbox.removeClass('active');
                    $(this).zsGetList().removeClass('active');
                }

                $('.zs-panel-list').each(function(){
                    if($(this).attr('list-id') !=zbox.attr('data-zbox-id')){
                        $(this).removeClass('active');
                    }
                })

            });
        }
    }
    $.fn.selectauto.defaults = $.extend({}, {
        inputEvents: { blur: _e_blur, click: _e_click, keydown: _events, keyup: _write_in },
        valueField: 'value',
        textField: 'text',
        setDisabled: false,
        setValue: '',
        keyHandler: {
            up: function(e) {
                var _t = $(e.target);
                _t.blur();
                up2down(_t, 'up');
            },
            down: function(e) {
                var _t = $(e.target);
                _t.blur();
                up2down(_t, 'down');
            },
            enter: function(e) {
                var _t = $(e.target);
                _t.selectauto('setInputVal');
                _t.blur();
                var _s = $('select.zbox-id-' + _t.parents('.zs-box').attr('data-zbox-id'));
                var zbox = _s.zsGetBox();
                zbox.removeClass('active');
                _s.zsGetList().removeClass('active');
            },
            query: function(e) {
                var _t = $(e.target);
                _t.selectauto('setInputVal');
            },
            close: function(e) {
                var _t = $(e.target);
                _t.blur();
                var _s = $('select.zbox-id-' + _t.parents('.zs-box').attr('data-zbox-id'));
                var zbox = _s.zsGetBox();
                zbox.removeClass('active');
                _s.zsGetList().removeClass('active');
            }
        }
    });
})();
/**
 * [description]
    // select下拉框的使用
    $(".search_key").on('setZsValue',function(){
        var _key = $(this).getZsValue();
        // console.log(_key);
    });

    $('.z-select').zSelect();//渲染下拉框
    $(".search_key").getZsValue();//下拉框的当前选中值
    $(".search_key").setZsValue('123');//设置下拉框的选中值
    $(".search_key").setZsDisabled(true); //下拉框不可选择

    // 设置下拉数据
    $(".search_key").zsSetData([
        {'text':'zsx1','value':'1'},
        {'text':'zsx2','value':'2'},
        {'text':'zsx3','value':'3'},
        {'text':'zsx4','value':'4'}
    ],{
        valueField: 'value',
        textField: 'text'
    }).setZsValue('');

    // ajax方式设置下拉数据
    $(".search_key").zsLoadData({
        'valueField': 'id',
        'textField': 'name',
        'url': '../resource/jsondata/new4s_xs_state.json',
    });

    $.zSelectGroup([{
        elem: $('.sg_province'),
        setValue:'21',
        setDisabled: true, //可以设置联动下拉框是否可点击
        valueField: 'id',
        textField: 'name',
        url: '../resource/jsondata/new4s_xs_province.json?level=1',
        dataFitler: function(result) {
            return result.data;
        }
    }, {
        elem: $('.sg_city'),
        setValue:'121',
        setDisabled: true, //可以设置联动下拉框是否可点击
        valueField: 'id',
        textField: 'name',
        url: '../resource/jsondata/new4s_xs_province.json?level=2&pid=@parentValue',
        dataFitler: function(result) {
            return result.data;
        }
    }]);

    //修改下拉框样式时 可以直接加data-style属性如下
    <select class="z-select" data-skin="w185" data-style="width:100px;" name="demo_province" id="demo_province" data-prompt="请选择省份"></select>

    //select下拉需要模糊搜索时要增加data-content="true"属性
    <select class="z-select" data-skin="w185 name="outuid" data-content="true" data-prompt="请选择用户...">
 */


;
(function($) {
    //全局函数
    $.extend({
        randomid: function() {
            //16位自由数
            var rdm = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'.split('');
            var x = new Array();
            for (var i = 0; i < 16; i++) {
                x.push(rdm[Math.floor(Math.random() * rdm.length)]);
            };
            return x.join('');
        },
        arrayfilter: function(arr) {
            //数组去重 获取品牌索引时使用
            var array = [];
            if (arr.length > 0) {
                /*array.push(arr[0]);
                $.map(arr, function(a, i) {
                    if (arr[i] != array[array.length - 1]) {
                        array.push(arr[i]);
                    }
                    return '';
                })*/
                $.map(arr, function(a, i) {
                    if ($.inArray(arr[i],array) == -1) {
                        array.push(arr[i]);
                    }
                    return '';
                })
            }
            return array.sort();
        },
        getDataScript: function(_objname, _url, cbk) {
            var _script = $('<script type="text\/javascript" src="' + _url + '?callback=window.loadselectdata"></script>');
            $('script[js-select]').length > 0 ?
                _script.insertBefore($('script[js-select]')) :
                _script.insertBefore($('body script').eq(0));

            window.loadselectdata = function(_result) {
                var _data = $('<script type="text\/javascript">window["' + _objname + '"]=' + JSON.stringify(_result) + '<\/script>');
                _data.insertAfter(_script);
                _script.remove();
                cbk(window[_objname]);
            }
        },
        getDataAjax: function(_url, cbk) {
            $.ajax({
                url: _url,
                type: 'get',
                //dataType: 'jsonp',
                success: function(result) {
                    if (result) {
                        cbk(result);
                    }
                }
            });
        },
        resizeList: function(){
            $('.zs-select-group').each(function(_i,_vt){
                if($(_vt).attr('relative-parent') == 'window'){
                    if(!$(_vt).oGetSelect().oGetContent()){return true;}
                    $(_vt).oGetSelect().oGetContent().css({
                        top:$(_vt).oGetSelect().offset().top -(-$(_vt).oGetSelect().innerHeight())+'px',
                        left:$(_vt).oGetSelect().offset().left+'px',
                        width:$(_vt).oGetSelect().innerWidth()+'px'
                    });
                }
            })
        }
    })

    $.fn.oselectDefaults = {
        cbkEvent: null,
        dataList: function(parms, index, cbk) {
            var box = this;
            var p = parms[index - 1];
            var pid = '';
            var newurl = p.url;
            if (index > 1) {
                pid = box.oGetContent().find('.select-box-content[data-level=' + (index - 1) + ']').data('data-checked-parms');
                pid = pid.id;
            }
            switch (p.type) {
                case 'default':
                case 'easyui':
                    newurl = p.url.replace('@parentValue', pid);
                    $.getDataAjax(newurl, cbk);
                    break;
                case 'javascript':
                    if (p.jsObject && p.jsObject != '') {
                        if (window[p.jsObject]) {
                            var _nresult = evalJsObject(window[p.jsObject]);
                            cbk(_nresult);
                        } else {
                            if (newurl && newurl != '') {
                                $.getDataScript(p.jsObject, newurl, cbk);
                            }
                        }
                    }
                    break;
                default:
                    break;
            };

            function evalJsObject(_result) {
                if (index > 1 && pid != '') {
                    $.each(_result, function(i, group) {
                        if (group[p.fieldv] == pid) {
                            _result = group['List'];
                        }
                    })
                }
                return _result;
            }

        },
        oEvents: {
            'toggleDown': function(_s) {
                _s.off('click').on('click', '.select-text', function(e) {
                    $('body').find('.zs-box').removeClass('active');
                    var _p = $(this).parent('.select-defined');
                    e.stopPropagation();
                    if (_p.hasClass('disabled')) {
                        return false;
                    }
                    if (_p.hasClass('active')) {
                        _p.removeClass('active').removeClass('active-top');
                        _p.oGetContent().removeClass('active').removeClass('active-top');
                    } else {
                        $('.select-defined').not(this).removeClass('active');
                        $('.select-defined-content').not('[panel-id="'+_p.attr('id').split('select-')[1]+'"]').removeClass('active');
                        _p.removeClass('active').removeClass('active-top').addClass('active');
                        _p.oGetContent().removeClass('active').removeClass('active-top').addClass('active');
                        if(_p.oGetContent().hasClass('relative-window-panel')){
                            _p.oGetContent().css({
                                top:_p.oGetSelect().offset().top -(-_p.oGetSelect().innerHeight())+'px',
                                left:_p.oGetSelect().offset().left+'px',
                                width:_p.oGetSelect().innerWidth()+'px'
                            });
                        }

                        //判断下拉底部高度是否可容纳list下拉列表的高度
                        _p.checkedListHeight();
                    }
                });
                $(document).not(_s).on('click', function(e) {
                    if ($(e.target).parents('.select-defined-content').length == 0) {
                        _s.removeClass('active');
                        _s.oGetContent().removeClass('active');
                    }
                });
            },
            'bindAbcClick': function(_s) {
                _s.off('click').on('click', 'a', function(e) {
                    e.stopPropagation();
                    var _this = $(e.target);
                    var _eq = _s.find('a').index(_this);
                    var _adcbox = _s.next('.select-dl');

                    if (_s.data('ds-index') == _eq) {
                        return;
                    }
                    _adcbox.scrollTop(0);
                    _s.data('ds-index', _eq);

                    var posTop = _adcbox.find('dl').eq(_eq).offset().top;
                    _adcbox.scrollTop(posTop - _adcbox.offset().top);
                });
            },
            'toggleDisn': function(_s, _box) {
                var _titBar = _box.oGetTitBar();
                var _index = parseInt(_s.attr('data-level'));
                $.each(_titBar.find('li'), function(i, item) {
                    if (i < (_index - 1)) {
                        $(item).removeClass('current').removeClass('disn');
                    }
                    if (i > (_index - 1)) {
                        $(item).removeClass('current').addClass('disn');
                    }
                    if (i == (_index - 1) && _index > 1) {
                        $(item).addClass('current').removeClass('disn');
                    }
                });
                _s.removeClass('disn').siblings(".select-box-content").addClass('disn');

                //判断下拉底部高度是否可容纳list下拉列表的高度
                $(_box).checkedListHeight();
            }

        }
    };
    $.fn.extend({
        oselect: function(opt, selectCbk) {
            var opts = opt ? opt : {};
            return $(this).each(function(idx, v) {
                var _v = $(v),
                    rdid = $.randomid(),
                    zselect = null;
                if (!_v.attr('inited')) {
                    //初始化
                    var d_tit = _v.attr('data-title') || '',
                        d_place = _v.attr('data-holder') || '',
                        d_skin = _v.attr('data-skin') || '',
                        d_style = _v.attr('data-style') || '',
                        d_name = _v.attr('name') || '';
                    var len = 0;
                    var tit_str = '';
                    if (d_tit != '') {
                        _v.data('d-title', d_tit.split(',')).removeAttr('data-title');
                        if (opts.length > 0) {
                            len = opts.length;
                        }
                        tit_str += _v.oSetTitle(len);
                    }
                    var zbox = $('<div class="select-text"><span>' + d_place + '</span><i class="zs-down-ico"></i></div>'),
                        zinput = $('<input type="hidden" name="' + d_name + '" />'),
                        zcontent = $('<div class="select-defined-content">' + ((tit_str != '') ? ('<div class="select-defined-title">' + tit_str + '</div>') : '') + '</div>');

                    zselect = $('<div id="select-' + rdid + '" class="select-defined ' + d_skin + '" ' + (d_style != '' ? ('style="' + d_style + '"') : ('')) + '></div>');
                    zselect.append(zbox).append(zinput);
                    if(_v.attr('relative-parent') !='window'){
                        zselect.append(zcontent);
                    }else{
                        zcontent.addClass('relative-window-panel').attr('panel-id',rdid).appendTo("html>body");
                    }
                    zselect.data('zbox_panel', zcontent);
                    _v.after(zselect).removeAttr('name');
                    _v.attr({
                        'inited': 'yes',
                        'data-id': rdid
                    });

                    $(window).on('resize',function(){
                        $.resizeList();
                    });
                    $.resizeList();
                }

                zselect = zselect ? zselect : _v.oGetSelect();
                if ($.isFunction(selectCbk)) {
                    zselect.off('selectCbk').on('selectCbk', selectCbk);
                }
                zselect.oGetContent().find('.select-clear').off('click').on('click',function(){
                    _v.clearGroupVal();
                    zselect.removeClass('active');
                    zselect.oGetContent().removeClass('active');
                });
                _v.hasClass('disabled') ? zselect.addClass('disabled') : zselect.removeClass('disabled');

                if (!opts || !opts.length) { return _v; }
                if ($.isArray(opts) && opts.length > 0) {
                    var sArr = [];
                    var sHased = false;
                    $.map(opts, function(itm, i) {
                        if (!itm.type) {
                            if (i > 0) {
                                opts[i]['type'] = opts[i - 1]['type'];
                            } else {
                                opts[i]['type'] = 'default';
                            }
                        }
                        if (itm.selected) { sHased = true; }
                        sArr.push(itm.selected ? itm.selected : '');
                        return '';
                    });
                    if (sHased) {
                        _v.attr('data-selected', sArr.join(','));

                    }
                    if (_v.attr('data-selected')) {
                        _v.data('setedVal', _v.attr('data-selected'));
                    }
                    zselect.data('d-data', opts);
                    zselect.oListData();
                }
                zselect.oListEvent('toggleDown');

            });
        },
        oSetTitle: function(_len) {
            var _t = $(this);
            var tit = _t.data("d-title");
            var _length = _len > 0 ? _len : tit.length;
            var x = ['<ul>'];
            for (var i = 1; i < (_length + 1); i++) {
                x.push(i == 1 ?
                    ('<li class="current">') :
                    ('<li class="disn"><i>&gt;</i>')
                );
                x.push('<a href="javascript:void(0)">' + tit[i - 1] + '</a></li>');
            }
            x.push('</ul><div class="select-clear">×</div>');
            return x.join('');
        },
        oGetSelect: function() {
            var _t = $(this);
            if (_t.is('select')) {
                var o_id = _t.attr('data-id');
                if (o_id) {
                    return _t.next('#select-' + o_id);
                } else {
                    return $();
                }
            } else if (_t.is('.select-defined')) {
                return _t;
            }
        },
        oGetTitBar: function() {
            return this.data('zbox_panel').find('.select-defined-title') || null;
        },
        oGetText: function() {
            return this.find('.select-text') || null;
        },
        oGetInput: function() {
            return this.find('.select-text').next('input[type="hidden"]') || null;
        },
        oGetContent: function() {
            return this.data('zbox_panel') || null;
        },
        oGetSelectText: function() {
            var txt = this.oGetSelect().oGetText().find('span').text();
            return (this.attr('data-holder') == txt) ? '' : txt;
        },
        oGetSelectVal: function() {
            return this.oGetSelect().oGetInput().val() || '';
        },
        oGetGroupVal: function() {
            return this.oGetSelect().data('select-checked-parms') || '';
        },
        oSetGroupVal: function() {
            var _t = this,
                _valArr = [],
                _rdom = _t.oGetSelect();
            if (!arguments || arguments.length == 0) { return _t; }
            $.each(arguments, function(i, v) {
                _valArr.push(v);
            });
            var _sdata = _rdom.data('d-data');
            $.each(_sdata, function(i, x) {
                if (_valArr[i]) {
                    _sdata[i].selected = _valArr[i];
                }
            });
            var $events = $._data(_rdom[0], 'events');
            if ($events && $events['selectCbk']) {
                _t.oselect(_sdata, $events['selectCbk']);
            } else {
                _t.oselect(_sdata);
            }
            return _t;
        },
        clearGroupVal: function() {
            var _oselect = this.oGetSelect();
            _oselect.oGetInput().val('');
            _oselect.oGetText().removeAttr('v')
                .find('span').text(this.attr('data-holder') || '请选择');

            _oselect.oGetTitBar().find('ul').find('li').eq(0).addClass('current').siblings('li').addClass('disn').removeClass('current');

            _oselect.oGetContent().find('.select-box-content').each(function(k, v) {
                $(v).removeData('data-checked-parms');
                if (k > 0) {
                    $(v).remove();
                } else {
                    $(v).removeClass('disn');
                    $(v).find('.select-dl').find('a.active').removeClass('active');
                }
            });
            this.removeAttr('data-selected');
            this.removeData('setedVal');
            this.oGetSelect().removeData('select-checked-parms');
            return this;
        },
        addDisabled: function() {
            this.addClass('disabled').oGetSelect().addClass('disabled');
            return this;
        },
        removeDisabled: function() {
            this.removeClass('disabled').oGetSelect().removeClass('disabled');
            return this;
        },
        oListData: function(index) {
            var _t = this;
            var datalist = $.fn.oselectDefaults.dataList;
            var crud = 'create';
            var opts = _t.data('d-data');
            var index = index ? index : 1;
            var list = _t.oGetContent().find('.select-box-content[data-level="' + index + '"]');
            if (!list || list.length == 0) {
                if (index <= opts.length) {
                    crud = 'create';
                } else {
                    crud = 'close';
                }
            } else if (list.length > 0) {
                crud = 'update';
            }

            if (crud == 'close') {
                _t.removeClass('active');
                _t.oGetContent().removeClass('active');
                var _ncons = _t.oGetContent().find('.select-box-content[data-level]');
                var _currentCked = [];
                var _lastCked = '';
                $.each(_ncons, function(x, y) {
                    _currentCked.push($(y).data('data-checked-parms'));
                    if ($(y).attr('data-level') == (index - 1)) {
                        _lastCked = $(y).data('data-checked-parms');
                        /*将选中的内容用斜线分开显示到框内start */
                        // _t.oGetInput().val(_lastCked.id);
                        // _t.oGetText().attr("v", "true").find('span').text(_lastCked.title);
                        /*将选中的内容用斜线分开显示到框内end */
                    }
                });
                _t.data('select-checked-parms', _currentCked);
                _t.prev('select').attr('data-selected', $.map(_currentCked, function(z) { return z.id }));
                _t.prev('select').removeData('setedVal');
                var $events = $._data(_t[0], 'events');
                if ($events && $events['selectCbk']) {
                    _lastCked.id != '' ?
                        _t.trigger('selectCbk', [_t, _lastCked.id, _lastCked.title]) :
                        _t.trigger('selectCbk', [_t, '', '']);
                }
                return _t;
            }

            var cruelist = {
                crud: function(way, __s, h) {
                    var abcPack = (h && h > 0) ? true : false;
                    switch (way) {
                        case 'create':
                            _t.oGetContent().append('<div class="select-box-content' + (abcPack ? ' abc-pack' : '') + '" data-level="' + index + '" ' + (abcPack ? "style=\"height:" + h + "px;\"" : "") + '>' + __s + '</div>');
                            if (abcPack) {
                                _t.oGetContent().find('.select-bar-ABC').oListEvent('bindAbcClick');
                            }
                            break;
                        case 'update':
                            var _ncon = _t.oGetContent().find('.select-box-content[data-level=' + index + ']');
                            _ncon.html(__s);
                            if (abcPack) {
                                _ncon.addClass('abc-pack').css('height', h + 'px');
                                _t.oGetContent().find('.select-bar-ABC').oListEvent('bindAbcClick');
                            } else {
                                _ncon.removeClass('abc-pack').css('height', 'auto');
                            }
                            break;
                        default:
                            break;
                    }
                    var ncon = _t.oGetContent().find('.select-box-content[data-level=' + index + ']');
                    ncon.oListEvent('bindListClick');
                    var _parents = (_t.prev('select').hasClass('zs-select-group')) ? _t.prev('select') : '';
                    var _selectedArr = _parents.data('setedVal') ? _parents.data('setedVal').split(',') : [];

                    if (_selectedArr.length > 0 && _selectedArr[index - 1] && _selectedArr[index - 1] != '0') {
                        ncon.find('a[data-key="' + _selectedArr[index - 1] + '"]').trigger('click');
                    }
                    $.fn.oselectDefaults.oEvents['toggleDisn'].call(this, ncon, _t);
                },
                evalAbc: function(arr) {
                    //品牌ABC索引
                    var __abc_str = '<div class="select-bar-ABC">';
                    for (var i = 0; i < arr.length; i++) {
                        __abc_str += '<a href="javascript:void(0);" data-abc="' + arr[i] + '">' + arr[i] + '</a>';
                    }
                    __abc_str += '</div>';
                    return __abc_str;
                }
            }

            datalist.call(this, opts, index, dcallback);

            function dcallback(result) {
                var ots = opts[index - 1];
                var fid = ots.fieldv || 'id',
                    ftitle = ots.fieldt || 'title';
                    fletterv = ots.fletter || 'fletter';
                var data = ots.filter instanceof Function ? ots.filter(result) : result;
                if (!data || data.length == 0) { return; }
                var str = '<div class="select-data-dl">';
                var abc = [];
                if (ots.abcTag) {
                    //abc
                    abc = $.arrayfilter($.map(data, function(a) { return (ots.type != 'javascript' ? (a[fletterv] || a[ftitle].substring(0, 1)) : a["L"]) || '' }));
                    if (abc.length > 0) {
                        str += cruelist['evalAbc'](abc);
                        str += '<div class="select-dl">';
                        for (var i = 0; i < abc.length; i++) {
                            str += '<dl><dt>' + abc[i] + '</dt><dd>';
                            $.each(data, function(_i, item) {
                                if ((ots.type != 'javascript' ? (item[fletterv] || item[ftitle].substring(0, 1)) : item["L"]) == abc[i]) {
                                    var fname = item[ftitle];
                                    if (ots.type != 'javascript' && !item[fletterv]) {
                                        fname = item[ftitle].slice(4);
                                    }
                                    str += '<a href="javascript:void(0);" data-key="' + item[fid] + '" data-text="' + fname + '" title="' + fname + '">' + fname + '</a>';
                                }
                            })
                            str += '</dd></dl>';
                        }
                        str += '</div>';
                    }
                }
                if (!ots.abcTag || abc.length == 0) {
                    str += '<div class="select-dl"><dl>';
                    $.each(data, function(_i, group) {
                        var fname = group[ftitle];
                        var flist = group['list'] || group['List'] || '';
                        if (flist && flist.length > 0 && index > 1) {
                            str += '<dt>' + fname + '</dt><dd>';
                            for (var i = 0; i < flist.length; i++) {
                                str += '<a href="javascript:void(0);" data-key="' + flist[i][fid] + '" data-text="' + flist[i][ftitle] + '" title="' + flist[i][ftitle] + '">' + flist[i][ftitle] + '</a>';
                            }
                            str += '</dd>';
                        } else {
                            if (_i == 0) {
                                str += '<dd>';
                            }
                            str += '<a href="javascript:void(0);" data-key="' + group[fid] + '" data-text="' + fname + '" title="' + fname + '">' + fname + '</a>';
                            if (_i == (data.length - 1)) {
                                str += '</dd>';
                            }
                        }
                    })
                    str += '</dl></div>';
                }

                str += '</div>';
                if (ots.abcTag) {
                    cruelist['crud'](crud, str, abc.length * 20);
                } else {
                    cruelist['crud'](crud, str);
                }
                _t.oListEvent('toggleLevel');
            }
        },
        oListEvent: function(type) {
            //事件分发
            var _t = this;
            var evts = $.fn.oselectDefaults.oEvents;
            switch (type) {
                case 'toggleDown':
                case 'bindAbcClick':
                    evts[type].call(this, _t);
                    break;
                case 'toggleLevel':
                    _t.oGetTitBar().off('click').on('click', 'ul li a', function(e) {
                        var _dom = $(e.target),
                            _li = _dom.parent('li');
                        var _level = _dom.parents('ul').find('li').index(_li);
                        if (_level > 0) {
                            _li.next('li').addClass('disn')
                                .siblings('li').removeClass('current');
                        } else {
                            _li.siblings('li').addClass('disn').removeClass('current');
                        }
                        _li.addClass('current');
                        var __contents = _dom.parents('.select-defined-content');
                        __contents.find('.select-box-content[data-level=' + (_level - (-1)) + ']').removeClass('disn')
                            .siblings('.select-box-content').addClass('disn');
                        _t.oGetSelect().checkedListHeight();
                    });
                    break;
                case 'bindListClick':
                    var _zselect = _t.parents('.select-defined');
                    if(_t.parents('.select-defined-content').hasClass('relative-window-panel')){
                        _zselect = $('#select-'+ _t.parents('.select-defined-content').attr('panel-id'));
                    }

                    var _level = parseInt(_t.attr('data-level'));
                    _t.off('click').on('click', '.select-dl dl dd a', function(e) {
                        var _dom = $(e.target);
                        var vkey = {};
                        vkey.id = _dom.attr('data-key');
                        vkey.title = _dom.attr('data-text');
                        _dom.parents('.select-dl').find('a.active').removeClass('active');
                        _dom.addClass('active');
                        var _ncons = _zselect.oGetContent().find('.select-box-content[data-level]');
                        $.each(_ncons, function(k, v) {
                            if ($(v).attr('data-level') > _level) {
                                $(v).removeData('data-checked-parms');
                            }
                        });
                        /*修改level选中的值 */
                        _t.data('data-checked-parms', vkey);

                        /*将选中的内容用斜线分开显示到框内start */
                        var _currentCked = [];
                        $.each(_ncons, function(x, y) {
                            if ($(y).data('data-checked-parms')) {
                                _currentCked.push($(y).data('data-checked-parms'));
                            }
                        });
                        var ids = $.map(_currentCked, function(z) { return z.id });
                        var titles = $.map(_currentCked, function(z) { return z.title }).join('/');
                        _zselect.oGetInput().val(ids);
                        _zselect.oGetText().attr("v", "true").find('span').text(titles);

                        _zselect.data('select-checked-parms', _currentCked);
                        _zselect.prev('select').attr('data-selected', ids);
                        /*将选中的内容用斜线分开显示到框内end */
                        _zselect.oListData(_level + 1);
                    });
                    break;
            }
        },
        checkedListHeight: function() {
            var _p = $(this);
            _p.removeClass('active-top');
            var _list = _p.oGetContent();
            if (_list.height() > $(window).outerHeight() - _list.offset().top) {
                var space_h = $(window).outerHeight() - _list.offset().top - 50;
                space_h > 260 ? _p.removeClass('active-top') : _p.addClass('active-top');
                _list.find('.select-box-content:visible').each(function(idx, eachlist) {
                    $(eachlist).css('height', 'auto');
                    space_h = space_h > 260 ? space_h : 260;
                    $(eachlist).css('height', (space_h > _list.height() ? _list.height() : space_h) + 'px');
                    if ($(eachlist).hasClass('abc-pack')) {
                        $(eachlist).find('.select-dl').css('min-height', $(eachlist).find('.select-bar-ABC').height() + 'px');
                    }
                });

            }
        }
    });
})(jQuery);
